package net.qqxh.resolve2text.impl;


import net.qqxh.resolve2text.File2TextResolve;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class Docx2TextResolve implements File2TextResolve {
    private static String TYPE = "docx";

    @Override
    public String resolve(byte[] data) {
        String text = "";
        InputStream fis = null;
        XWPFDocument doc;
        doc = null;
        XWPFWordExtractor workbook = null;
        try {
            fis = new ByteArrayInputStream(data);
            doc = new XWPFDocument(fis);
            workbook = new XWPFWordExtractor(doc);
            text = workbook.getText();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return text;
    }

    @Override
    public String getType() {
        return TYPE;
    }
}
